package com.woke.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.woke.CheckpaypswActivity;
import com.example.woke1.PhonefriendActivity;
import com.http.HttpMethods;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.woke.diyview.Alertdialogall;
import com.woke.method.Checkpaypsw;
import com.woke.method.Intentnet;
import com.woke.method.MyApp;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class Caixtong2Fragment extends Fragment implements OnClickListener, OnItemClickListener{
	
	private View layout;
	private LayoutInflater minflater;
	private Czhilreciver reciver;
	private MyApp application;
	private GridView mGridView;
	private Chongzliuadapter adapter;
	private TextView mTphone;//�������
	private TextView mTwhere ;//
	private EditText mEphone;//�ֶ������ֻ��
	private ImageView mIlist;
	private boolean isshuru ;//�ж��Ƿ����ֶ�����
	
	private String phoneno;//����Ҫ��ֵ���ֻ��
	private String phonenoing;//�����ֻ�Ź�̿��ܸı��
	private String face_price;//��ֵ��ֵ
	private String cz_price;//������
	
	private RelativeLayout mLayout;
	private TextView mTok;
	private TextView mTmliu,mTzm1,mTsllm;
	private int clickTemp;
	
	private String province;
	private String operators;
	private ArrayList<String> list_hf = new ArrayList<String>();
	private ArrayList<String> list_hfp = new ArrayList<String>();
	
	private RelativeLayout mBar;
	
	private String pid;//ƽ̨���
	private View nowifi;
	private Intentnet net;
	
	private Alertdialogall zidingy;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		if(layout == null){
			minflater = inflater;
			layout = minflater.inflate(R.layout.cxtong1_layout, null);
			intview();
		}else{
			ViewGroup parent = (ViewGroup) layout.getParent();
			if(parent!=null){
				parent.removeView(layout);
			}
		} 
		return layout;
	}

	private void intview() {
		net = new Intentnet();
		reciver = new Czhilreciver();
		IntentFilter filter = new IntentFilter();
		filter.addAction("com.woke.cxtonglactivity");
		getActivity().registerReceiver(reciver, filter);
		
		zidingy = new Alertdialogall();
		mBar = (RelativeLayout) layout.findViewById(R.id.fmcxtf_frame1);
		
		application = (MyApp) getActivity().getApplication();
		mGridView = (GridView) layout.findViewById(R.id.fmcxtong_f1_gridview);
		adapter = new Chongzliuadapter();
		mGridView.setAdapter(adapter);
		mGridView.setOnItemClickListener(this);
		mTphone = (TextView) layout.findViewById(R.id.fmcxtong_f1_phone1);
		mTwhere = (TextView) layout.findViewById(R.id.fmcxtong_f1_where);
		mEphone = (EditText) layout.findViewById(R.id.fmcxtong_f1_ephone);
		if(application.getDatas_load ()!=null){
		phoneno = application.getDatas_load().getUser_login();
		mTphone.setText(phoneno.substring(0, 3)+" "+phoneno.substring(3, 7)
					+" "+phoneno.substring(phoneno.length()-4, phoneno.length()));
		}

		mIlist = (ImageView) layout.findViewById(R.id.fmcxtong_f1_phonelist);
		nowifi = layout.findViewById(R.id.fmcxtong_when_nowifi);
		nowifi.setOnClickListener(this);
		mLayout = (RelativeLayout) layout.findViewById(R.id.fm_cxt1_relative1);
		mTsllm = (TextView) layout.findViewById(R.id.fmcxtong_relative_sellm);//���ۼ۸�
		mTmliu = (TextView) layout.findViewById(R.id.fmcxtong_relative_m);//������
		mTzm1 = (TextView) layout.findViewById(R.id.fmcxtong_relative_zm1);//ԭ�۸�
		mTok = (TextView) layout.findViewById(R.id.fmcxtong_relative_ok);//ȷ��
		mIlist.setOnClickListener(this);
		mTphone.setOnClickListener(this);
		mTok.setOnClickListener(this);
		if(net.isNetworkConnected(getActivity()) == false){
			Toast.makeText(getActivity(), "网络链接不可用", Toast.LENGTH_SHORT).show();
			nowifi.setVisibility(View.VISIBLE);
		}else{
			qurrayprivicen(phoneno);
		}
		mEphone.addTextChangedListener(watcher);
	}
	
	private TextWatcher watcher = new TextWatcher() {
		private int startwordno;
		private int endwordno;
	    @Override
	    public void onTextChanged(CharSequence s, int start, int before, int count) {
	    	
	    }
	    @Override
	    public void beforeTextChanged(CharSequence s, int start, int count,
	            int after) {
	    }
	    
	    @Override
	    public void afterTextChanged(Editable s) {
	    	startwordno = mEphone.getSelectionStart();
	    	endwordno = mEphone.getSelectionEnd();
	    	if(mEphone.getText().toString().trim().length() >  11){
	    		s.delete(startwordno - 1, endwordno); 
	            int tempSelection = endwordno; 
	            mEphone.setText(s); 
	            mEphone.setSelection(tempSelection); 
	    		Log.e("11", "11");
	    	}else if(mEphone.getText().toString().trim().length() == 11){
	    		phoneno = s.toString().trim();
//	    		phonenoing = phoneno;
	    		Log.e("phoneno", phoneno);
	    		qurrayprivicen(phoneno);
	    	}
	    }
	};
	private void qurrayprivicen(final String phone) {
		if(application.getDatas_load ()==null)return;
		AsyncHttpClient ahc = new AsyncHttpClient();
        PersistentCookieStore myCookieStore = new PersistentCookieStore(getActivity());    
        ahc.setCookieStore(myCookieStore); 
		RequestParams params = new RequestParams();
		params.put("g", "api");
		params.put("m", "mobile");
		params.put("a", "queryProvince");
		params.put("mobile", phone);
		ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler(){

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				Log.e("电话归宿地", "的"+response);
				try {
					String flag = response.getString("flag");
					if(flag.equals("success")){
						JSONObject jsonObject = response.getJSONObject("data");
						JSONObject object = jsonObject.getJSONObject("data");
						String provinceid = object.getString("provinceid");
						province = object.getString("province");
						String operatorsid = object.getString("operatorsid");
						operators = object.getString("operators");
						if(phone.equals(application.getDatas_load().getUser_login())){
							mTwhere.setText("账号绑定号码"+"("+province+operators+")");
						}else{
							mTwhere.setText("("+province+operators+")");
						}
						qurraydatalist(operatorsid);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure(statusCode, headers, responseString, throwable);
			}
			
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
			}
			
			@Override
			public void onFinish() {
				super.onFinish();
			}
		});
	}
	
	private void qurraydatalist(String operatorsid) {
		AsyncHttpClient ahc = new AsyncHttpClient();
        PersistentCookieStore myCookieStore = new PersistentCookieStore(getActivity());    
        ahc.setCookieStore(myCookieStore); 
		RequestParams params = new RequestParams();
		params.put("g", "api");
		params.put("m", "mobile");
		params.put("a", "queryInfoByType");
		params.put("oid", operatorsid);
		params.put("type", "2");
		ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler(){
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				Log.e("套餐", "套餐"+response);
				try {
					String flag = response.getString("flag");
					if(flag.equals("success")){
						nowifi.setVisibility(View.GONE);
						list_hf.clear();
						list_hfp.clear();
						JSONObject jsonObject = response.getJSONObject("data");
						JSONObject object = jsonObject.getJSONObject("data");
						String id = object.getString("id");
						pid = object.getString("pid");
						String packages = object.getString("liulian");
						String hfprice = object.getString("llprice");
						String[] hf1 = packages.split("\\|");
						for (int i = 0; i < hf1.length; i++) {
							String string = hf1[i];
							list_hf.add(string);
						}
						String[] hfp1 = hfprice.split("\\|");
						for (int i = 0; i < hfp1.length; i++) {
							String string = hfp1[i];
							list_hfp.add(string);
						}
					}else{
						nowifi.setVisibility(View.VISIBLE);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
				if(list_hf.size() > 0 && list_hfp.size() > 0){
					adapter.notifyDataSetChanged();
				}
				
			}
			
			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure(statusCode, headers, responseString, throwable);
				nowifi.setVisibility(View.VISIBLE);
			}
			
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
			}
			
			@Override
			public void onFinish() {
				super.onFinish();
			}
		});
	}
	
	private void cxtchongzhil(String pid) {
		if(application.getDatas_load ()==null)return;
		AsyncHttpClient ahc = new AsyncHttpClient();
        PersistentCookieStore myCookieStore = new PersistentCookieStore(getActivity());    
        ahc.setCookieStore(myCookieStore); 
		RequestParams params = new RequestParams();
		params.put("g", "api");
		params.put("m", "mobile");
		params.put("a", "liulianChargeByType");
		params.put("account_no", phoneno);
//		params.put("account_no", "13622990770");//�����������
		params.put("packageSize", cz_price);//������
		params.put("money", face_price);
		params.put("pid", pid);
		params.put("user_id", application.getDatas_load().getId());
		Log.e("params", params.toString());
		ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler(){
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				Log.e("充值", "充值"+response);
				try {
					String flag = response.getString("flag");
					String info = response.getString("info");
					if(flag.equals("success")){
						Toast.makeText(getActivity(), ""+info, Toast.LENGTH_SHORT).show();
						getActivity().finish();
					}else{
						Toast.makeText(getActivity(), ""+info, Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure(statusCode, headers, responseString, throwable);
				Toast.makeText(getActivity(), "充值失败", Toast.LENGTH_SHORT).show();
			}
			
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
				mBar.setVisibility(View.VISIBLE);
			}
			
			@Override
			public void onFinish() {
				super.onFinish();
				mBar.setVisibility(View.GONE);
			}
		});
	}

	class Czhilreciver extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			
			Bundle extras = intent.getExtras();
			String phoneno1 = extras.getString("phoneno").toString().trim();
			if(phoneno1.equals("phoneno")){
				cxtchongzhil(pid);
			}else{
				phoneno = phoneno1;
				if(net.isNetworkConnected(getActivity()) == false){
					Toast.makeText(getActivity(), "网络链接不可用", Toast.LENGTH_SHORT).show();
					nowifi.setVisibility(View.VISIBLE);
				}else{
					qurrayprivicen(phoneno);
				}
					if(isshuru == false){
						mTphone.setText(phoneno1.substring(0, 3)+" "+phoneno1.substring(3, 7)
								+" "+phoneno1.substring(phoneno1.length()-4, phoneno1.length()));
					}else{
						Log.e("phoneno1", phoneno1);
						mEphone.setText(phoneno1.substring(0, 3)+" "+phoneno1.substring(3, 7)
								+" "+phoneno1.substring(phoneno1.length()-4, phoneno1.length()));	
					}
//				}
			}
		}
	}
	
	class Chongzliuadapter extends BaseAdapter{

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list_hf.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}
		
		public void setSeclection(int position) {
			clickTemp = position;
			}
		
		class Holder {
//			ImageView mIicon;
			TextView mTmoney;
			TextView mThowmcuh;
			RelativeLayout mReachange;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
//			Holder holder = null;
//			if(convertView == null){
//				holder = new Holder();
				convertView = getActivity().getLayoutInflater().inflate(R.layout.item_gridview_liul, null);
				RelativeLayout mReachange = (RelativeLayout) convertView.findViewById(R.id.item_grid_cxtrelative);
				TextView mTmoney = (TextView) convertView.findViewById(R.id.item_czhiadter_moneyl);
				TextView mThowmcuh = (TextView) convertView.findViewById(R.id.item_czhiadter_howmuchl);
//				convertView.setTag(holder);
//			}else{
//				 holder = (Holder) convertView.getTag();
//			}
			String hf_str = list_hf.get(position);
			mTmoney.setText(hf_str+"M");
			
			// ����ı�ѡ��listItem�ı���ɫ
			if (clickTemp == position) {
				mReachange.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_sxzylinered));
			mTmoney.setTextColor(getResources().getColor(R.color.lightred));
			} else {
				mReachange.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_sxzyline));
			mTmoney.setTextColor(getResources().getColor(R.color.texthint));
			}
//			String hf_strp = list_hfp.get(position);
//			holder.mThowmcuh.setText("�ۼۣ�"+hf_strp+"元");
			
			return convertView;
		}
	}
	
	public class PopupWindows extends PopupWindow {

		public PopupWindows(Context mContext, String phoneno, final String cz_price) {

			View view = View
					.inflate(mContext, R.layout.item_popu_cxt, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById(R.id.popowind_cxt_zhifu);
			LayoutParams params = ll_popup.getLayoutParams();
			params.height = application.screenHigth / 3 * 2;
			params.width = application.screenWidth;
			ll_popup.setLayoutParams(params);
			ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_bottom_in_2));

			setWidth(LayoutParams.FILL_PARENT);
			setHeight(LayoutParams.FILL_PARENT);
			setBackgroundDrawable(new BitmapDrawable());
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(view, Gravity.BOTTOM, 0, 0);
			update();
//			popowind_cxt_zhifuok
			TextView mTextinfo = (TextView) view.findViewById(R.id.popowind_cxt_textinfo);
			TextView mTextmone = (TextView) view.findViewById(R.id.popowind_cxt_textmoney);
			mTextinfo.setText(phoneno+province+operators+cz_price+"M流量充值");
			mTextmone.setText(face_price+"元");
			view.findViewById(R.id.popowind_cxt_finish).setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View view) {
					dismiss();
				}
			});
			view.findViewById(R.id.popowind_cxt_zhifuok).setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(getActivity(),CheckpaypswActivity.class);
					intent.putExtra("paymoney", face_price);
					intent.putExtra("cxtong", "liuliang");
					startActivity(intent);
					dismiss();
				}
			});
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.fmcxtong_f1_phonelist:
			isshuru = false;
			mTphone.setVisibility(View.VISIBLE);
			mEphone.setVisibility(View.GONE);
			Intent intent = new Intent(getActivity(),PhonefriendActivity.class);
			intent.putExtra("from", "where1");
			startActivity(intent);
			break;
			
		case R.id.fmcxtong_f1_phone1:
			isshuru = true;
			mTphone.setVisibility(View.GONE);
			mEphone.setVisibility(View.VISIBLE);
			mTwhere.setText("");
			break;
			
		case R.id.fmcxtong_relative_ok:
			if(isshuru == false){
				 phoneno = mTphone.getText().toString().replace(" ", "");
			}else{
				phoneno = mEphone.getText().toString().replace(" ", "");
			}
			new PopupWindows(getActivity(),phoneno,cz_price);
		break;
		
		case R.id.fmcxtong_when_nowifi:
			if(net.isNetworkConnected(getActivity()) == false){
				Toast.makeText(getActivity(), "网络链接不可用", Toast.LENGTH_SHORT).show();
				nowifi.setVisibility(View.VISIBLE);
			}else{
				qurrayprivicen(phoneno);
			}
			break;

		default:
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		
		Checkpaypsw check = new Checkpaypsw();
		if(check.check(application) == true){
			zidingy.aralogid(getActivity(), "还未设置支付密码","前往设置？");
		}else{
		String string = list_hf.get(arg2);//������
		String string2 = list_hfp.get(arg2);//��Ӧ�۸�
		cz_price = string;
		face_price = string2;
		mTsllm.setText(string2+"元");
		mTmliu.setText(string+"M");
		mTzm1.setText(string2+"元");
		mLayout.setVisibility(View.VISIBLE);
		if(isshuru == false){
			 phoneno = mTphone.getText().toString().trim();
		}else{
			phoneno = mEphone.getText().toString().trim();
		}
		
		adapter.setSeclection(arg2);
		adapter.notifyDataSetChanged();
	}
	}
}
